// const userApi = require ('./api/admin/userApi.js');
// const menuApi = require ('./api/admin/menuApi.js');
const express = require('express');
const bodyParser = require('body-parser');
const consola = require('consola');
const router = express.Router();
const db = require('../server/db');
const { Nuxt, Builder } = require('nuxt');
const jwt = require('jwt-simple');
const app = express();
const moment = require('moment');
const session = require('express-session');
const cookieParser = require('cookie-parser');
const fs = require('fs');
const path = require('path');


// Import and Set Nuxt.js options
const config = require('../nuxt.config.js');
config.dev = process.env.NODE_ENV !== 'production';

async function start() {
    // Init Nuxt.js
    const nuxt = new Nuxt(config);

    const { host, port } = nuxt.options.server;

    // Build only in dev mode
    if (config.dev) {
        const builder = new Builder(nuxt);
        await builder.build();
    } else {
        await nuxt.ready();
    }
    app.set('trust proxy', 1);
    app.use(
        session({
            secret: 'vinnyBlog',
            name: 'testapp', //这里的name值得是cookie的name，默认cookie的name是：connect.sid
            cookie: { maxAge: 1000 * 60 * 60 * 12 }, //设置maxAge是80000ms，即80s后session和相应的cookie失效过期
            resave: true,
            rolling: true,
            saveUninitialized: false,
        })
    );
    app.use(cookieParser());
    app.use(bodyParser.urlencoded({ extended: true }));
    // app.use (bodyParser.json ());
    app.use(bodyParser.json({ limit: '50mb' }));
    app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
    app.all('/api/*', function(req, res, next) {
        let token = req.session.token;
        if (req.url.indexOf('login') >= 0) {
            next();
        } else if (req.url.indexOf('/api/') >= 0) {
            let now = moment().valueOf();
            if (token) {
                var decoded = jwt.decode(token, 'secret', true);
                req.session.userName = decoded.iss;
                if (now > decoded.exp) {
                    res.send({ code: 501, data: {}, msg: '登录已过期,请重新登录' });
                    // res.redirect('/login')
                } else {
                    if (req.cookies.token != token) {
                        res.send({ code: 501, data: {}, msg: '登录已过期,请重新登录' });
                    } else {
                        next();
                    }
                }
            } else {
                res.send({ code: 501, data: {}, msg: 'token已失效果请重新登录' });
                // res.redirect(config+'/login')
                // res.end();
            }
        } else {
            next();
        }
    });

    var filePath = path.resolve();
    // var fileArr = [];
    console.log('filePath', filePath);
    fs.readdir(filePath + '/server/api', function(err, files) {
        if (err) {
            console.log(err);
            return;
        }
        for (key in files) {
            if (files[key] != '.DS_Store') {
                fs.readdir(filePath + '/server/api/' + files[key], function(
                    err,
                    files2
                ) {
                    for (index in files2) {
                        app.use(
                            '/api/admin',
                            require('./api/' + files[key] + '/' + files2[index])
                        );
                    }
                    app.use(nuxt.render);
                });
            }
        }
    });
    // 后端api路由
    // Listen the server
    app.listen(port, host);
    consola.ready({
        message: `Server listening on http://${host}:${port}`,
        badge: true,
    });
}
start();